import { defineStore } from "pinia";
import { userInfoReponseData } from "@/api/user/type.ts";
import { reqLogin } from "@/api/user";
import { SET_TOKEN } from "@/util/token";

const useUserStore = defineStore("User", {
  state: (): any => {
    return {
      token: "",
      username: ""
    };
  },
  actions: {
    //用户登录的方法
    async userLogin(data: any) {
      //登录请求
      const result: userInfoReponseData = await reqLogin(data);
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      console.log(result);
      if (result.code == 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data.token;
        this.username = result.data.name;
        SET_TOKEN(result.data.token);
        localStorage.setItem("id", String(result.data.id));
        //能保证当前async函数返回一个成功的promise
        return "ok";
      } else {
        return Promise.reject(new Error(result.message));
      }
    }
  },
  getters: {}
});

export default useUserStore;
